package lambda;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.*;

/**
 * @author : DuJiabao
 * @Date : 2021/3/19 16:26
 * @Project : java_learning
 * @File : null.java
 * @Desc :
 */
public class LambdaTest {

  @Test
  public void test2() {
    // 匿名内部类的方法
    MathCalculate<Integer> mathCalculate = new MathCalculate<>() {
      @Override
      public int method(Integer a, Integer b) {
        return a + b;
      }
    };
    int res = mathCalculate.method(1, 2);
    System.out.println(res); // 3
  }

  @Test
  public void test() {
    // Lambda表达式的方法
    MathCalculate<Integer> mathCalculate = (x, y) -> x + y;
    int res = mathCalculate.method(1, 2);
    System.out.println(res);
  }

  @Test
  public void runnableTest() {
    //Runnable runnable = () -> System.out.println("你好世界");
    //Runnable runnable = () ->
    //{
    //  System.out.println("你好世界");
    //  System.out.println("第二个你好世界");
    //};
    //RunnableUser runnableUser = new RunnableUser();
    //runnableUser.useRunnable(runnable);
    //runnable.run();

    RunnableUser runnableUser = new RunnableUser();
    runnableUser.useRunnable(() -> System.out.println("你好世界"));
  }

  @Test
  public void consumerTest() {
    Consumer<String> talk = System.out::println;
    //Consumer<String> talk = str -> System.out.println(str);
    talk.accept("你好世界");
  }

  @Test
  public void supplierTest() {
    Supplier<String> getSomething = () -> "你好世界";
    String res = getSomething.get();
    System.out.println(res);
  }

  @Test
  public void functionTest() {
    Function<String, Integer> Parse = Integer::parseInt;
    Integer integer = Parse.apply("10");
    System.out.println(integer);
  }

  @Test
  public void predicateTest() {
    Predicate<Integer> filter = (num) -> num >= 100;
    System.out.println(filter.test(100));
    System.out.println(filter.test(77));
    System.out.println(filter.test(110));
  }

  @Test
  public void quoteTest() {
    List<Integer> integers = Arrays.asList(1, 2, 3, 44, 5, 6);
    integers.forEach(System.out::println);
  }

  @Test
  public void compareTest() {
    //BiPredicate<String, String> comparator = String::equals;
    BiPredicate<String, String> comparator = (x, y) -> x.equals(y);
    boolean res = comparator.test("hello", "hello");
    System.out.println(res);
  }

  @Test
  public void newTest() {
    Supplier<User> supplier = User::new;  // 无参构造
    User user = supplier.get();
    System.out.println(user);

    Function<Integer,User> function = User::new;  // 有参构造
    user = function.apply(1);
    System.out.println(user);
  }

  @Test
  public void newArrayTest() {
    Function<Integer,Integer[]> function = Integer[]::new;
    Integer[] apply = function.apply(2);
    System.out.println(apply.length);  // 2
    System.out.println(Arrays.toString(apply));  // [null, null]
  }
}
